package com.feng.cloud.job.executor.configure;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.feng.cloud.common.constants.SystemConstant;
import com.feng.cloud.common.constants.auth.AuthConstant;
import com.feng.cloud.common.exception.AuthException;
import com.feng.cloud.common.exception.auth.AuthStatus;
import com.feng.cloud.common.service.RedisService;
import com.feng.cloud.job.executor.feign.AuthService;
import com.google.common.net.HttpHeaders;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName RequestInterceptorConfigure
 * @Description TODO
 * @Author Better Feng
 * @Date 2020/1/17 16:47
 * @Version 1.0
 **/
@Configuration
public class RequestInterceptorConfigure implements RequestInterceptor {

    @Value("${authorization.client.id:feng-service-job}")
    private String AUTHORIZATION_CLIENT_ID;
    @Value("${authorization.client.secret:123456}")
    private String AUTHORIZATION_CLIENT_SECRET;
    @Value("${authorization.gateway.url:http://localhost:8000/auth/oauth/token}")
    private String AUTHORIZATION_GATEWAY_URL;

    @Autowired
    private RedisService redisService;
    @Autowired
    private AuthService authService;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 处理token
        Object token = redisService.get(AuthConstant.FENG_SERVICE_JOB_TOKEN);
        if (token == null) {
            // 重新申请token
            String result = HttpRequest.post(AUTHORIZATION_GATEWAY_URL)
                    .basicAuth(AUTHORIZATION_CLIENT_ID, AUTHORIZATION_CLIENT_SECRET)
                    .form("grant_type", "client_credentials").execute().body();
            if (StringUtils.isBlank(result)) {
                throw new AuthException(AuthStatus.AUTHORIZED_SERVER_ERROR);
            }
            JSONObject jsonObject = JSONObject.parseObject(result);

            if (jsonObject == null) {
                throw new AuthException(AuthStatus.USERNAME_OR_PASSWORD_ERROR);
            }
            token = jsonObject.getString("access_token");
            // 保存redis
            Long expiresIn = jsonObject.getLong("expires_in");
            if (expiresIn > 60) {
                expiresIn = expiresIn - 60;
            }
            redisService.set(AuthConstant.FENG_SERVICE_JOB_TOKEN, token, expiresIn);
        }
        requestTemplate.header(HttpHeaders.AUTHORIZATION, SystemConstant.OAUTH2_TOKEN_TYPE + token);
    }
}
